﻿using System;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Tools.Helper;

namespace Tools
{
    public partial class FileOper : MUserControl
    {
        string[] folderFilter = null;
        string[] fileFilter = null;

        public FileOper()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            XmlNodeList nodelist1 = Config.GetConfigObject("/root/FileOper/ignorefolders");
            XmlNodeList nodelist2 = Config.GetConfigObject("/root/FileOper/ignorefiles");
            if (nodelist1 != null && nodelist1.Count > 0)
                folderFilter = nodelist1[0].InnerText.Split(';');
            if (nodelist2 != null && nodelist2.Count > 0)
                fileFilter = nodelist2[0].InnerText.Split(';');
        }

        #region [[ tabPage1 ]]

        private void button1_Click_1(object sender, EventArgs e)
        {
            ToolHelper.SelectFolder(this.t1txt1, folderBrowserDialog1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!ToolHelper.IsSelectValidate(t1txt1, t1lbl1, SelectType.Folder))
                return;

            string path = t1txt1.Text.Trim();
            DirectoryInfo dir = new DirectoryInfo(path);
            List<string> list = new List<string>();
            GetFileList(dir, list);
            if (list.Count == 0)
            {
                t1lbl1.Text = "无满足条件的文件";
                return;
            }
            int index = path.Length + 1;
            int listCount = list.Count;
            for (int i = 0; i < listCount; i++)
            {
                list[i] = list[i].Substring(index);
            }

            list.Sort();
            string fpath = Path.Combine(path, DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
            File.WriteAllLines(fpath, list);
            t1lbl1.Text = string.Format("文件列表已输出到文件：{0}\r\n文件个数：{1}", fpath, listCount);
            System.Diagnostics.Process.Start(fpath);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!ToolHelper.IsSelectValidate(t1txt2, t1lbl2, SelectType.File))
                return;

            string path = t1txt2.Text.Trim();
            string[] lines = File.ReadAllLines(path);
            List<string> list = lines.ToList();
            if (list == null) return;
            list.Sort();
            var result = list.Distinct();
            File.WriteAllLines(path, result);
            t1lbl2.Text = string.Format("操作已完成，文件个数：{0}", result.Count());
            System.Diagnostics.Process.Start(path);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ToolHelper.SelectFile(this.t1txt2, openFileDialog1);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ToolHelper.SelectFolder(this.t1txt3, folderBrowserDialog1);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ToolHelper.SelectFolder(this.t1txt4, folderBrowserDialog1);
        }

        private void button8_Click(object sender, EventArgs e)
        {
            ToolHelper.SelectFile(this.t1txt5, openFileDialog1);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (!ToolHelper.IsSelectValidate(t1txt3, t1lbl3, SelectType.Folder))
                return;
            if (!ToolHelper.IsSelectValidate(t1txt4, t1lbl3, SelectType.Folder))
                return;
            if (!ToolHelper.IsSelectValidate(t1txt5, t1lbl3, SelectType.File))
                return;

            string spath = this.t1txt3.Text.Trim();
            string dpath = this.t1txt4.Text.Trim();
            string fpath = this.t1txt5.Text.Trim();

            string[] flist = File.ReadAllLines(fpath);
            var list = flist.Distinct();
            foreach (var item in list)
            {
                string str = item.Trim();
                if (string.IsNullOrWhiteSpace(str)) continue;
                string sourceFileName = Path.Combine(spath, str);
                string targetFileName = Path.Combine(dpath, str);

                FileInfo f = new FileInfo(targetFileName);
                if (!f.Directory.Exists)
                {
                    Directory.CreateDirectory(f.Directory.FullName);
                }

                if (f.Exists) f.Attributes = FileAttributes.Normal;

                File.Copy(sourceFileName, targetFileName, true);
            }

            t1lbl3.Text = string.Format("复制完成 {0}", DateTime.Now.ToString("HH:mm:ss"));
        }

        private void GetFileList(DirectoryInfo dir, List<string> list)
        {
            FileInfo[] flist = dir.GetFiles();
            DirectoryInfo[] dirlist = dir.GetDirectories();

            foreach (var item in flist)
            {
                if (fileFilter != null && fileFilter.AsQueryable().Any(p => string.Compare(p.Trim(), item.Extension, true) == 0))
                    continue;

                if (item.LastWriteTime > this.t1time1.Value)
                    list.Add(item.FullName);
            }




            foreach (var item in dirlist)
            {
                if (folderFilter != null && folderFilter.AsQueryable().Any(p => string.Compare(p.Trim(), item.Name, true) == 0))
                    continue;

                GetFileList(item, list);
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            ToolHelper.SelectFolder(this.t1txt6, folderBrowserDialog1);
        }

        private void t1btn10_Click(object sender, EventArgs e)
        {
            if (!ToolHelper.IsSelectValidate(t1txt6, t1lbl4, SelectType.Folder))
                return;

            string path = this.t1txt6.Text.Trim();
            DirectoryInfo dir = new DirectoryInfo(path);
            SetBinObjWriteable(dir);

            t1lbl4.Text = "操作完成";
        }

        private void SetBinObjWriteable(DirectoryInfo dir)
        {
            if (string.Compare(dir.Name, "bin", true) == 0 || string.Compare(dir.Name, "obj", true) == 0)
            {
                foreach (var item in dir.GetFiles())
                {
                    item.Attributes = FileAttributes.Normal;
                }
            }

            foreach (var item in dir.GetDirectories())
            {
                SetBinObjWriteable(item);
            }
        }

        private void t1btn11_Click(object sender, EventArgs e)
        {
            if (!ToolHelper.IsSelectValidate(t1txt2, t1lbl2, SelectType.File))
                return;

            string path = t1txt2.Text.Trim();
            string[] lines = File.ReadAllLines(path);
            List<string> list = BuildMapHelper.GetBuildMapFile(lines);

            if (list == null) return;
            list.Sort();
            var result = list.Distinct();

            FileInfo f = new FileInfo(path);

            string outputfile = Path.Combine(f.Directory.FullName, string.Format("{0}_r{1}", f.Name.Substring(0, f.Name.LastIndexOf('.')), f.Extension));
            File.WriteAllLines(outputfile, result);
            t1lbl2.Text = string.Format("操作已完成，文件个数：{0}", result.Count());
            System.Diagnostics.Process.Start(outputfile);
        }

        #endregion
    }
}
